<template>
  <div class="app-page">
    <el-table-form ref="form" :model="query">
      <el-form-item label="责任机构:" prop="orgSNNo">
        <el-tree-select
          v-model="query.orgSNNo"
          :clearable="false"
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择',
            loading: $loadingPlugin.getTreeData
          }"
          :tree-params=" {
            'default-expand-all': true,
            'expand-on-click-node': false,
            'highlight-current': true,
            props:{
              value:'orgSNNo',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData
          }"
          @node-click="selectTreeChange"
        />
      </el-form-item>
      <el-form-item label="处理人:" prop="userId">
        <el-select v-model="query.userId" :loading="$loadingPlugin.getOwnersList" clearable filterable style="width: 100%;" placeholder="请选择">
          <el-option
            v-for="item in ownersList"
            :key="item.userId"
            :label="item.userName"
            :value="item.userId"
          />
        </el-select>
      </el-form-item>
      <el-form-item :table-form-merge="2" label="下单时间:" prop="createTime">
        <el-date-picker
          v-model="date"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="yyyy-MM-dd HH:mm"
          :clearable="false"
        />
      </el-form-item>
      <template v-slot:btns>
        <el-button type="primary" icon="el-icon-search" @click="search">查询</el-button>
      </template>
    </el-table-form>
    <div style="margin-bottom: 10px;" class="btn-group">
      <div />
      <div>
        <el-select v-model="query.queryType" style="width: 150px;">
          <el-option :value="1" label="按规格型号" />
          <el-option :value="2" label="按用户类型" />
        </el-select>
      </div>
    </div>
    <lb-table
      ref="lbTable"
      v-loading="$loadingPlugin.fetchData"
      class="table"
      border
      highlight-current-row
      element-loading-text="加载中"
      :column="tableData.column"
      :data="tableData.data"
      :pagination="false"
      :show-summary="isShowSummary"
      :summary-method="getSummaries"
      height="100%"
      @fetch="fetchData"
    />
  </div>
</template>

<script>
  import { queryDistributionCountList, queryMap, queryOwnersList } from '@/api'
  import getTreeData from '@/utils/jsonTree'
  import { mapGetters } from 'vuex'
  import moment from 'dayjs'
  import { formatColumnMap, parseTime } from '@/utils'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'

  export default {
    name: 'constributionCount',
    data() {
      return {
        currentOrg: null,
        isShowSummary: false,
        treeData: [],
        ownersList: [],
        csmTypeMap: [],
        date: [moment().startOf('day'), moment().endOf('day')],
        query: {
          orgSNNo: '', // 所属机构orgSNNo
          userId: '',
          queryType: 1
        },
        tableData: {
          total: 0,
          column: [{
            type: 'index'
          }, {
            label: '配送员',
            prop: 'senderName'
          }, {
            label: '所属机构',
            prop: 'orgName'
          }],
          data: []
        },
        originData: []
      }
    },
    computed: {
      ...mapGetters([
        'orgList', 'corpSettingData'
      ])
    },
    watch: {
      'originData': function(val) {
        if (val.length === 0 || this.csmTypeMap.length === 0) return
        let columns = []
        if (this.query.queryType === 1) {
          if (this.query.userId > 0) {
            columns = columns.concat([
              {
                type: 'index'
              }, {
                label: '下单日期',
                prop: 'happendDt',
                render: (h, { row }) => <span>{row.happendDt && parseTime(row.happendDt, '{y}-{m}-{d}')}</span>
              }
            ])
          } else {
            columns = columns.concat([
              {
                type: 'index'
              }, {
                label: '配送员',
                prop: 'senderName'
              }, {
                label: '所属机构',
                prop: 'orgName'
              }
            ])
          }
          var gridDataArray = []
          var gridDataObj = {}

          var _columns = {}
          val.forEach((item, index) => {
            var xh = item.bottleXH || '其他'
            _columns[xh] = 'field' + index
          })
          for (const c in _columns) {
            if (_columns.hasOwnProperty(c)) {
              columns.push({
                label: c,
                align: 'right',
                prop: _columns[c],
                formatter: this.formatter
              })
              val.forEach(it => {
                const data = it
                const xh = data.bottleXH || '其他'
                if (this.query.userId > 0) {
                  gridDataObj[data.happendDt] = gridDataObj[data.happendDt] || data
                  gridDataObj[data.happendDt][_columns[c]] = gridDataObj[data.happendDt][_columns[c]] || 0
                  if (xh === c) {
                    gridDataObj[data.happendDt][_columns[c]] += data.bottleCount
                  }
                } else {
                  gridDataObj[data.senderName + data.orgSNNo] = gridDataObj[data.senderName + data.orgSNNo] || data
                  gridDataObj[data.senderName + data.orgSNNo][_columns[c]] = gridDataObj[data.senderName + data.orgSNNo][_columns[c]] || 0
                  if (xh === c) {
                    gridDataObj[data.senderName + data.orgSNNo][_columns[c]] += data.bottleCount
                  }
                }
              })
            }
          }
          columns.push({
            label: '合计(瓶)',
            prop: 'senderTotal',
            align: 'right',
            sortable: true
          })
          for (const code in gridDataObj) {
            if (gridDataObj.hasOwnProperty(code)) {
              gridDataArray.push(gridDataObj[code])
            }
          }
          // 横向汇总
          if (gridDataArray.length > 0) {
            gridDataArray.forEach(i => {
              const obj = i
              let senderTotal = 0
              for (const key in obj) {
                if (key.indexOf('field') !== -1) {
                  senderTotal += obj[key]
                }
              }
              obj.senderTotal = senderTotal
            })
          }
          // 纵向汇总
          const footer = {}
          if (this.query.userId > 0) {
            footer.happendDt = '合计'
          } else {
            footer.senderName = '合计'
          }
          for (var f in _columns) {
            var key = _columns[f]
            var ftotal = 0
            for (var i = 0; i < gridDataArray.length; i++) {
              ftotal += gridDataArray[i][key]
            }
            footer[key] = ftotal
          }
          this.isShowSummary = true
        } else {
          if (this.query.userId > 0) {
            columns = columns.concat([
              {
                type: 'index'
              }, {
                label: '下单日期',
                prop: 'transactDt',
                render: (h, { row }) => <span>{row.transactDt && parseTime(row.transactDt, '{y}-{m}-{d}')}</span>
              }
            ])
          } else {
            columns = columns.concat([
              {
                type: 'index'
              }, {
                label: '配送员',
                prop: 'ownerName'
              }, {
                label: '所属机构',
                prop: 'orgName'
              }
            ])
          }
          this.isShowSummary = false
          const datas = {}
          const csmtype = {}
          let subItem = {}
          val.forEach(item => {
            if (this.query.userId > 0) {
              if (!datas[item.transactDt]) {
                datas[item.transactDt] = { transactDt: item.transactDt }
              }
              subItem = datas[item.transactDt]
            } else {
              if (!datas[item.ownerName + '-' + item.orgName]) {
                datas[item.ownerName + '-' + item.orgName] = { ownerName: item.ownerName, orgName: item.orgName }
              }
              subItem = datas[item.ownerName + '-' + item.orgName]
            }
            if (!subItem[String(item.csmType)] && item.csmType) {
              subItem[String(item.csmType)] = item.newChipCount
            }
            if (!csmtype[String(item.csmType)] && item.csmType) {
              csmtype[String(item.csmType)] = true
              const t = formatColumnMap(this.csmTypeMap, 'value', item.csmType, 'desc')
              columns.push({ label: t, prop: String(item.csmType), align: 'right' })
            }
          })
          const tempdatas = []
          for (const key in datas) {
            tempdatas.push(datas[key])
          }
          this.tableData.data = tempdatas
        }
        this.tableData.column = columns
      }
    },
    async created() {
      await Promise.all([this.getTreeData(), this.queryOptionsMap()])
    },
    methods: {
      // 获取所属机构数据
      async getTreeData() {
        const data = this.orgList.map(item => ({
          label: item.orgName,
          ...item
        }))
        this.treeData = getTreeData(data)
        this.query.orgSNNo = this.treeData[0].orgSNNo
        await this.getOwnersList(this.treeData[0].orgId)
      },
      // 选择所属机构
      selectTreeChange(value) {
        this.currentOrg = value
        this.$set(this.query, 'userId', '')
        this.getOwnersList(value.orgId)
      },
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      async fetchData() {
        const query = {
          ...this._getQuery(this.query),
          currentPage: 1,
          pageSize: 999
        }
        if (this.date && this.date.length > 0) {
          query.transactTime = moment(this.date[0]).format()
          query.transactTimeEnd = moment(this.date[1]).format()
        }
        const diff = moment(this.date[1]).diff(moment(this.date[0]), 'days')
        if (diff > 93) {
          this.$message.warning('下单时间最大支持查询3个月')
          return
        }
        const res = await queryDistributionCountList(query)
        this.originData = res.data
        this.tableData.data = res.data
      },
      // 查询处理人列表
      async getOwnersList(org) {
        const b = this.corpSettingData.sp1 >> 2 & 0x01
        const res = await queryOwnersList({
          orgId: org || -1,
          corpparm1: b
        })
        this.ownersList = res.data
      },
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 查询枚举
      async queryOptionsMap() {
        const res = await mergeAsyncFunc(queryMap, { enumName: 'CustomerType' })
        this.csmTypeMap = res.data // 客户类型
      },
      formatter(row, column) {
        if (row[column.property] && row[column.property] !== 0) return row[column.property]
      },
      getSummaries(param) {
        const { columns, data } = param
        const sums = []
        columns.forEach((column, index) => {
          if (index === 1) {
            sums[index] = '合计'
            return
          }
          const values = data.map(item => Number(item[column.property]))
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
          }
        })

        return sums
      }
    }
  }
</script>

<style lang="scss" scoped>
.el-form-item .el-form-item {
  margin-bottom: 0;
}
.merge-item {
  /deep/ .el-form-item__content {
    display: flex;
  }
}
.btn-group {
  display: flex;
  justify-content: space-between;
}
.table {
  height: calc(100% - 160px);
  /deep/ .el-table {
    height: 100%;
  }
}
</style>
